#!/bin/bash

# PowerBank系统 - RocketMQ消息队列部署脚本
# 版本: 1.0.0
# 日期: 2025-01-07

set -e

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 配置变量
ROCKETMQ_VERSION="5.1.0"
ROCKETMQ_HOME="/opt/rocketmq"
ROCKETMQ_USER="rocketmq"
NAMESRV_PORT="9876"
BROKER_PORT="10911"
ADMIN_PORT="17890"

echo -e "${GREEN}=== PowerBank RocketMQ 部署脚本 ===${NC}"

# 函数：打印信息
print_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 函数：检查命令是否存在
check_command() {
    if ! command -v $1 &> /dev/null; then
        print_error "$1 命令未找到，请先安装"
        exit 1
    fi
}

# 函数：检查Java环境
check_java() {
    print_info "检查Java环境..."
    if ! command -v java &> /dev/null; then
        print_error "Java未安装，请先安装JDK 17+"
        exit 1
    fi
    
    JAVA_VERSION=$(java -version 2>&1 | awk -F '"' '/version/ {print $2}' | awk -F. '{print $1}')
    if [ "$JAVA_VERSION" -lt 17 ]; then
        print_error "需要JDK 17或更高版本，当前版本: $JAVA_VERSION"
        exit 1
    fi
    
    print_info "Java环境检查通过: $(java -version 2>&1 | head -n 1)"
}

# 函数：下载RocketMQ
download_rocketmq() {
    print_info "下载RocketMQ $ROCKETMQ_VERSION..."
    
    cd /tmp
    ROCKETMQ_FILE="rocketmq-all-${ROCKETMQ_VERSION}-bin-release.zip"
    
    if [ ! -f "$ROCKETMQ_FILE" ]; then
        print_info "正在下载 $ROCKETMQ_FILE ..."
        wget "https://archive.apache.org/dist/rocketmq/${ROCKETMQ_VERSION}/${ROCKETMQ_FILE}" || {
            print_error "下载失败，尝试从备用地址下载..."
            wget "https://dlcdn.apache.org/rocketmq/${ROCKETMQ_VERSION}/${ROCKETMQ_FILE}" || {
                print_error "下载失败，请检查网络连接或手动下载"
                exit 1
            }
        }
    else
        print_info "文件已存在，跳过下载"
    fi
}

# 函数：安装RocketMQ
install_rocketmq() {
    print_info "安装RocketMQ到 $ROCKETMQ_HOME ..."
    
    # 创建安装目录
    sudo mkdir -p $ROCKETMQ_HOME
    sudo chown $USER:$USER $ROCKETMQ_HOME
    
    # 解压
    cd /tmp
    unzip -q rocketmq-all-${ROCKETMQ_VERSION}-bin-release.zip
    cp -r rocketmq-all-${ROCKETMQ_VERSION}-bin-release/* $ROCKETMQ_HOME/
    
    # 设置执行权限
    chmod +x $ROCKETMQ_HOME/bin/*.sh
    
    print_info "RocketMQ安装完成"
}

# 函数：配置RocketMQ
configure_rocketmq() {
    print_info "配置RocketMQ..."
    
    # 配置NameServer
    cat > $ROCKETMQ_HOME/conf/namesrv.conf << EOF
# NameServer配置
listenPort=${NAMESRV_PORT}
serverWorkerThreads=8
serverCallbackExecutorThreads=0
serverSelectorThreads=3
serverOnewaySemaphoreValue=256
serverAsyncSemaphoreValue=64
bindAddress=0.0.0.0
EOF

    # 配置Broker
    cat > $ROCKETMQ_HOME/conf/broker.conf << EOF
# Broker配置
brokerClusterName=PowerBankCluster
brokerName=broker-a
brokerId=0
deleteWhen=04
fileReservedTime=120
brokerRole=ASYNC_MASTER
flushDiskType=ASYNC_FLUSH

# 网络配置
namesrvAddr=localhost:${NAMESRV_PORT}
brokerIP1=127.0.0.1
listenPort=${BROKER_PORT}

# 存储配置
storePathRootDir=${ROCKETMQ_HOME}/store
storePathCommitLog=${ROCKETMQ_HOME}/store/commitlog
storePathConsumeQueue=${ROCKETMQ_HOME}/store/consumequeue
storePathIndex=${ROCKETMQ_HOME}/store/index

# 性能配置
sendMessageThreadPoolNums=128
pullMessageThreadPoolNums=128
queryMessageThreadPoolNums=8
adminBrokerThreadPoolNums=16
clientManagerThreadPoolNums=32
consumerManagerThreadPoolNums=32

# 消息配置
maxMessageSize=4194304
mapedFileSizeCommitLog=1073741824
mapedFileSizeConsumeQueue=300000
EOF

    # 配置JVM参数
    cat > $ROCKETMQ_HOME/bin/runserver.sh << 'EOF'
#!/bin/sh

JAVA_OPT="${JAVA_OPT} -server -Xms2g -Xmx2g -Xmn1g -XX:MetaspaceSize=128m -XX:MaxMetaspaceSize=320m"
JAVA_OPT="${JAVA_OPT} -XX:+UseConcMarkSweepGC -XX:+UseCMSCompactAtFullCollection -XX:CMSInitiatingOccupancyFraction=70 -XX:+CMSParallelRemarkEnabled -XX:SoftRefLRUPolicyMSPerMB=0 -XX:+CMSClassUnloadingEnabled -XX:SurvivorRatio=8 -XX:+DisableExplicitGC"
JAVA_OPT="${JAVA_OPT} -verbose:gc -Xloggc:${ROCKETMQ_HOME}/logs/rmq_srv_gc.log -XX:+PrintGCDetails"
JAVA_OPT="${JAVA_OPT} -XX:-OmitStackTraceInFastThrow"
JAVA_OPT="${JAVA_OPT} -XX:-UseLargePages"
JAVA_OPT="${JAVA_OPT} -Djava.ext.dirs=${JAVA_HOME}/jre/lib/ext:${ROCKETMQ_HOME}/lib"
JAVA_OPT="${JAVA_OPT} -cp ${ROCKETMQ_HOME}/conf:${CLASSPATH}"

$JAVA ${JAVA_OPT} $@
EOF

    cat > $ROCKETMQ_HOME/bin/runbroker.sh << 'EOF'
#!/bin/sh

JAVA_OPT="${JAVA_OPT} -server -Xms2g -Xmx2g -Xmn1g"
JAVA_OPT="${JAVA_OPT} -XX:+UseG1GC -XX:G1HeapRegionSize=16m -XX:G1ReservePercent=25 -XX:InitiatingHeapOccupancyPercent=30 -XX:SoftRefLRUPolicyMSPerMB=0"
JAVA_OPT="${JAVA_OPT} -verbose:gc -Xloggc:${ROCKETMQ_HOME}/logs/rmq_broker_gc.log -XX:+PrintGCDetails -XX:+PrintGCDateStamps -XX:+PrintGCApplicationStoppedTime -XX:+PrintAdaptiveSizePolicy"
JAVA_OPT="${JAVA_OPT} -XX:+UseGCLogFileRotation -XX:NumberOfGCLogFiles=5 -XX:GCLogFileSize=30m"
JAVA_OPT="${JAVA_OPT} -XX:-OmitStackTraceInFastThrow"
JAVA_OPT="${JAVA_OPT} -XX:+AlwaysPreTouch"
JAVA_OPT="${JAVA_OPT} -XX:MaxDirectMemorySize=15g"
JAVA_OPT="${JAVA_OPT} -XX:-UseLargePages -XX:-UseBiasedLocking"
JAVA_OPT="${JAVA_OPT} -Djava.ext.dirs=${JAVA_HOME}/jre/lib/ext:${ROCKETMQ_HOME}/lib"
JAVA_OPT="${JAVA_OPT} -cp ${ROCKETMQ_HOME}/conf:${CLASSPATH}"

$JAVA ${JAVA_OPT} $@
EOF

    chmod +x $ROCKETMQ_HOME/bin/runserver.sh
    chmod +x $ROCKETMQ_HOME/bin/runbroker.sh
    
    # 创建日志目录
    mkdir -p $ROCKETMQ_HOME/logs
    mkdir -p $ROCKETMQ_HOME/store
    
    print_info "RocketMQ配置完成"
}

# 函数：创建系统服务
create_systemd_services() {
    print_info "创建RocketMQ系统服务..."
    
    # NameServer服务
    sudo tee /etc/systemd/system/rocketmq-namesrv.service > /dev/null << EOF
[Unit]
Description=RocketMQ Name Server
After=network.target

[Service]
Type=simple
User=$USER
Group=$USER
ExecStart=$ROCKETMQ_HOME/bin/mqnamesrv -c $ROCKETMQ_HOME/conf/namesrv.conf
ExecStop=/bin/kill -TERM \$MAINPID
Restart=on-failure
RestartSec=30
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target
EOF

    # Broker服务
    sudo tee /etc/systemd/system/rocketmq-broker.service > /dev/null << EOF
[Unit]
Description=RocketMQ Broker
After=network.target rocketmq-namesrv.service
Requires=rocketmq-namesrv.service

[Service]
Type=simple
User=$USER
Group=$USER
ExecStart=$ROCKETMQ_HOME/bin/mqbroker -c $ROCKETMQ_HOME/conf/broker.conf
ExecStop=/bin/kill -TERM \$MAINPID
Restart=on-failure
RestartSec=30
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target
EOF

    sudo systemctl daemon-reload
    sudo systemctl enable rocketmq-namesrv
    sudo systemctl enable rocketmq-broker
    
    print_info "系统服务创建完成"
}

# 函数：启动RocketMQ
start_rocketmq() {
    print_info "启动RocketMQ服务..."
    
    # 启动NameServer
    sudo systemctl start rocketmq-namesrv
    print_info "等待NameServer启动..."
    sleep 10
    
    # 检查NameServer状态
    if sudo systemctl is-active --quiet rocketmq-namesrv; then
        print_info "NameServer启动成功！"
    else
        print_error "NameServer启动失败，请检查日志: sudo journalctl -u rocketmq-namesrv"
        exit 1
    fi
    
    # 启动Broker
    sudo systemctl start rocketmq-broker
    print_info "等待Broker启动..."
    sleep 10
    
    # 检查Broker状态
    if sudo systemctl is-active --quiet rocketmq-broker; then
        print_info "Broker启动成功！"
    else
        print_error "Broker启动失败，请检查日志: sudo journalctl -u rocketmq-broker"
        exit 1
    fi
}

# 函数：创建PowerBank业务Topic
create_topics() {
    print_info "创建PowerBank业务Topic..."
    
    # 等待服务完全启动
    sleep 5
    
    # Topic列表
    topics=(
        "PowerBank-User-Topic"
        "PowerBank-Payment-Topic"
        "PowerBank-Order-Topic"
        "PowerBank-Device-Topic"
        "PowerBank-Finance-Topic"
        "PowerBank-Notification-Topic"
    )
    
    for topic in "${topics[@]}"; do
        print_info "创建Topic: $topic"
        $ROCKETMQ_HOME/bin/mqadmin updateTopic -n localhost:${NAMESRV_PORT} -t $topic -c PowerBankCluster -r 4 -w 4
    done
    
    print_info "Topic创建完成"
}

# 函数：验证安装
verify_installation() {
    print_info "验证RocketMQ安装..."
    
    # 检查服务状态
    if sudo systemctl is-active --quiet rocketmq-namesrv && sudo systemctl is-active --quiet rocketmq-broker; then
        print_info "✓ RocketMQ服务运行正常"
    else
        print_error "✗ RocketMQ服务状态异常"
        return 1
    fi
    
    # 列出Topic
    print_info "当前Topic列表:"
    $ROCKETMQ_HOME/bin/mqadmin topicList -n localhost:${NAMESRV_PORT} || true
    
    # 检查集群状态
    print_info "集群状态:"
    $ROCKETMQ_HOME/bin/mqadmin clusterList -n localhost:${NAMESRV_PORT} || true
}

# 函数：安装RocketMQ Console
install_console() {
    print_info "安装RocketMQ Console..."
    
    cd /tmp
    CONSOLE_FILE="rocketmq-console-ng-2.0.0.jar"
    
    if [ ! -f "$CONSOLE_FILE" ]; then
        print_info "下载RocketMQ Console..."
        wget "https://github.com/apache/rocketmq-externals/releases/download/rocketmq-console-1.0.0/rocketmq-console-ng-2.0.0.jar" || {
            print_warning "Console下载失败，跳过安装"
            return 0
        }
    fi
    
    # 复制到RocketMQ目录
    cp "$CONSOLE_FILE" "$ROCKETMQ_HOME/console/"
    
    # 创建Console启动脚本
    cat > "$ROCKETMQ_HOME/bin/start-console.sh" << EOF
#!/bin/bash
cd $ROCKETMQ_HOME/console
java -jar rocketmq-console-ng-2.0.0.jar --server.port=17890 --rocketmq.config.namesrvAddr=localhost:${NAMESRV_PORT}
EOF
    
    chmod +x "$ROCKETMQ_HOME/bin/start-console.sh"
    
    print_info "RocketMQ Console安装完成"
    print_info "启动命令: $ROCKETMQ_HOME/bin/start-console.sh"
    print_info "访问地址: http://localhost:${ADMIN_PORT}"
}

# 主函数
main() {
    echo -e "${GREEN}开始部署RocketMQ消息队列...${NC}"
    
    # 检查依赖
    check_command "wget"
    check_command "unzip"
    check_java
    
    # 执行部署步骤
    download_rocketmq
    install_rocketmq
    configure_rocketmq
    create_systemd_services
    start_rocketmq
    create_topics
    verify_installation
    install_console
    
    echo -e "${GREEN}=== RocketMQ部署完成 ===${NC}"
    echo -e "${GREEN}NameServer: localhost:${NAMESRV_PORT}${NC}"
    echo -e "${GREEN}Broker: localhost:${BROKER_PORT}${NC}"
    echo -e "${GREEN}Console: http://localhost:${ADMIN_PORT}${NC}"
    echo ""
    echo -e "${YELLOW}管理命令:${NC}"
    echo -e "${YELLOW}  启动: sudo systemctl start rocketmq-namesrv rocketmq-broker${NC}"
    echo -e "${YELLOW}  停止: sudo systemctl stop rocketmq-broker rocketmq-namesrv${NC}"
    echo -e "${YELLOW}  重启: sudo systemctl restart rocketmq-namesrv rocketmq-broker${NC}"
    echo -e "${YELLOW}  状态: sudo systemctl status rocketmq-namesrv rocketmq-broker${NC}"
}

# 执行主函数
main "$@"